﻿using System;
using System.Data;
using System.Text.RegularExpressions;
using System.Reflection;

namespace DatabaseService
{
    /// <summary>
    /// 全局公共方法集合
    /// </summary>
    public class Common
    {
        /// <summary>
        /// 字符串转换int
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int getInt(string str)
        {
            int id = 0;
            Int32.TryParse(str, out id);
            return id;
        }
        /// <summary>
        /// 字符串转换long
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static long getLong(string str)
        {
            long id = 0;
            long.TryParse(str, out id);
            return id;
        }
        /// <summary>
        /// 字符串转换double
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static double getDouble(string str)
        {
            double temp = 0;
            Double.TryParse(str, out temp);
            return temp;
        }

        /// <summary>
        /// 字符串转换float
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static float getFloat(string str)
        {
            Single.TryParse(str, out float temp);
            return temp;
        }

        /// <summary>
        /// 字符串转换为decimal
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static decimal getDecimal(string str)
        {
            decimal temp = 0;
            Decimal.TryParse(str, out temp);
            return temp;
        }

        /// <summary>
        /// 字符串转换为Datetime
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static DateTime getDateTime(string str)
        {
            DateTime temp = Convert.ToDateTime("1900-1-1");
            //modi by ylq 20.11.12 sybase默认只能1900/1/1
            //DateTime.TryParse(str, out temp);
            if (!DateTime.TryParse(str, out temp))
                temp = Convert.ToDateTime("1900-1-1");
            return temp;
        }

        /// <summary>
        /// 返回当前时间的yyyy/MM/dd HH:mm:ss
        /// </summary>
        /// <returns></returns>
        public static string getDateTimeStr()
        {
            string dateTimeStr = "";
            try
            {
                dateTimeStr = Convert.ToDateTime(DateTime.Now).ToString("yyyy/MM/dd HH:mm:ss");
            }
            catch (Exception)
            { }
            return dateTimeStr;
        }

        /// <summary>
        /// 固定返回yyyy/MM/dd HH:mm:ss
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string getDateTimeStr(object obj)
        {
            string dateTimeStr = "";
            try
            {
                dateTimeStr = Convert.ToDateTime(obj).ToString("yyyy/MM/dd HH:mm:ss");
            }
            catch (Exception)
            { }
            return dateTimeStr;
        }

        /// <summary>
        /// 时间格式转时间戳
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static long DateTimeStringToTimestamp(string dateTime)
        {
            long unixTimeStamp = 1478162177;
            try
            {
                if (string.IsNullOrEmpty(dateTime) || !DateTime.TryParse(dateTime, out DateTime dt))
                    return unixTimeStamp;
                DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); // 当地时区
                long timeStamp = (long)(dt - startTime).TotalSeconds; // 相差秒数
                return timeStamp;
            }
            catch (Exception)
            {
                return unixTimeStamp;
            }
        }

        /// <summary>
        /// 字符串与boolean值转换
        /// </summary>
        /// <param name="set"></param>
        /// <returns></returns>
        public static bool strToBool(string set)
        {
            set = set.Trim();
            if (set == null || set.Length != 1)
                return false;
            else
            {
                if ("T".Equals(set.ToUpper()))
                    return true;
                else
                    return false;
            }
        }

        /// <summary>
        /// boolean值与字符串转换
        /// </summary>
        /// <param name="set"></param>
        /// <returns></returns>
        public static string boolToStr(bool set)
        {
            if (set)
                return "T";
            else
                return "F";
        }

        /// <summary>
        /// 测试是否为数字
        /// </summary>
        /// <param name="numStr"></param>
        /// <returns></returns>
        public static bool checkNumber(string numStr, int low, int high)
        {
            int result;
            return (Int32.TryParse(numStr, out result) && result >= low && result <= high);
        }

        /// <summary>
        /// 计算字符串长度，中文占两位，英文字符占一位
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>规范化后的长度</returns>
        public static int strLen(string str)
        {
            double count = 0;
            int strLen = 0;
            Regex regex = new Regex("^[\u4e00-\u9fa5]$");
            char[] noWChar = str.ToCharArray();
            Regex regex1 = new Regex("[，：。”“？、！‘’（）《》【】；]");//中文标点符号也要占两个字节


            for (int j = 0; j < noWChar.Length; j++)
            {
                if (regex.IsMatch(noWChar[j].ToString()) || regex1.IsMatch(noWChar[j].ToString()))// 中文字符及中文标点

                    count = count + 2;
                else// 非中文字符

                    count++;
            }

            strLen = (int)count;
            return strLen;
        }
        /// <summary>
        /// 计算时间差
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="h"></param>
        /// <param name="m"></param>
        /// <param name="s"></param>
        /// <param name="ms"></param>
        /// <returns></returns>
        public static string getRunTime(long startTime, bool h, bool m, bool s, bool ms)
        {
            long useTime = DateTime.Now.Ticks - startTime;
            //LogToFile.threadToFile(Thread.CurrentThread.Name, "useTime=" + useTime);
            string str = "用时：";
            if (h)
            {
                str += useTime / (10000L * 1000L * 60L * 60L) + "h";
                useTime = useTime % (10000L * 1000L * 60L * 60L);
            }
            if (m)
            {
                str += useTime / (10000L * 1000L * 60L) + "m";
                useTime = useTime % (10000L * 1000L * 60L);
            }
            if (s)
            {
                str += useTime / (10000L * 1000L) + "s";
                useTime = useTime % (10000L * 1000L);
            }
            if (ms)
            {
                str += useTime / (10000L) + "ms";
                useTime = useTime % (10000L);
            }
            str += useTime + "ws";

            return str;
        }

        /// <summary>
        /// datatable给对象赋值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objmodel"></param>
        /// <param name="dtRow"></param>
        /// <returns></returns>
        public static T TableRowToModel<T>(T objmodel, DataRow dtRow)
        {
            //获取model的类型
            Type modelType = typeof(T);
            //获取model中的属性
            PropertyInfo[] modelpropertys = modelType.GetProperties();
            //遍历model每一个属性并赋值DataRow对应的列
            foreach (PropertyInfo pi in modelpropertys)
            {
                //获取属性名称
                String name = pi.Name;
                if (dtRow.Table.Columns.Contains(name))
                {
                    //非泛型
                    if (!pi.PropertyType.IsGenericType)
                    {
                        pi.SetValue(objmodel, string.IsNullOrEmpty(dtRow[name].ToString()) ? null : Convert.ChangeType(dtRow[name].ToString().Trim(), pi.PropertyType), null);
                        //pi.SetValue(objmodel, string.IsNullOrEmpty(dtRow[name].ToString().Trim()) ? null : Convert.ChangeType(dtRow[name].ToString().Trim(), pi.PropertyType), null);
                    }
                    //泛型Nullable<>
                    else
                    {
                        Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition();
                        //model属性是可为null类型，进行赋null值
                        if (genericTypeDefinition == typeof(Nullable<>))
                        {
                            //返回指定可以为 null 的类型的基础类型参数
                            pi.SetValue(objmodel, string.IsNullOrEmpty(dtRow[name].ToString().Trim()) ? null : Convert.ChangeType(dtRow[name].ToString().Trim(), Nullable.GetUnderlyingType(pi.PropertyType)), null);
                        }
                    }
                }
            }
            return objmodel;
        }
    }
}
